package com.dormitory.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.dormitory.activity.AddNotificationActivity;
import com.dormitory.activity.FileActivity;
import com.dormitory.activity.FriendDormitoryActivity;
import com.dormitory.activity.LoginActivity;
import com.dormitory.activity.MainActivity;
import com.dormitory.activity.MemberActivity;
import com.dormitory.adapter.NotificationListAdapter;
import com.dormitory.R;
import com.dormitory.application.MyApplication;
import com.dormitory.bean.DormitoryBean;
import com.dormitory.bean.NotificationBean;
import com.dormitory.bean.UserBean;
import com.dormitory.controller.DormitoryController;
import com.dormitory.controller.UserController;
import com.melnykov.fab.FloatingActionButton;

import org.json.JSONException;

import java.io.IOException;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link DormitoryFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DormitoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DormitoryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**************自己加的by jhf*****************/
    private ImageButton mButtonFile;
    private ImageButton mButtonMember;
    private ImageButton mButtonDormitory;
    private ListView mNotificationList;
    private NotificationListAdapter mNortificationListAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private FloatingActionButton mFab;
    private Handler updateHandler;


    public DormitoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DormitoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DormitoryFragment newInstance(String param1, String param2) {
        DormitoryFragment fragment = new DormitoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_dormitory, container, false);

        mButtonFile = (ImageButton) view.findViewById(R.id.file_button);
        mButtonMember = (ImageButton) view.findViewById(R.id.member_button);
        mButtonDormitory = (ImageButton) view.findViewById(R.id.dormitory_button);
        mNotificationList = (ListView)view.findViewById(R.id.notification_list);
        swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipe);
        (mFab = (FloatingActionButton)view.findViewById(R.id.fab)).attachToListView(mNotificationList);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final Activity activity = getActivity();
        mButtonFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, FileActivity.class);
                startActivity(intent);
            }
        });
        mButtonMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = -1;
                DormitoryBean dormitoryBean = ((MyApplication)activity.getApplication()).getDormitory();
                if(dormitoryBean != null)
                    id = dormitoryBean.getId();
                Intent intent = new Intent(activity, MemberActivity.class);
                intent.putExtra("dormitoryId", id);
                startActivity(intent);
            }
        });
        mButtonDormitory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = -1;
                DormitoryBean dormitoryBean = ((MyApplication)activity.getApplication()).getDormitory();
                if(dormitoryBean != null)
                    id = dormitoryBean.getId();
                Intent intent = new Intent(activity, FriendDormitoryActivity.class);
                intent.putExtra("dormitoryId", id);
                startActivity(intent);
            }
        });
        mNortificationListAdapter = new NotificationListAdapter(activity);
        mNotificationList.setAdapter(mNortificationListAdapter);

        swipeRefreshLayout.setColorSchemeResources(R.color.google_blue, R.color.google_green, R.color.google_red, R.color.google_yellow);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        DormitoryBean dormitoryBean = ((MyApplication)activity.getApplication()).getDormitory();
                        if(dormitoryBean != null) {
                            NotificationAsyncTask notificationAsyncTask = new NotificationAsyncTask(mNortificationListAdapter, activity);
                            notificationAsyncTask.execute(dormitoryBean.getId());
                        }
                        else
                            swipeRefreshLayout.setRefreshing(false);
                    }
                }, 800);

            }
        });
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, AddNotificationActivity.class);
                startActivity(intent);
            }
        });

        DormitoryBean dormitoryBean = ((MyApplication)activity.getApplication()).getDormitory();
        if(dormitoryBean != null) {
            NotificationAsyncTask notificationAsyncTask = new NotificationAsyncTask(mNortificationListAdapter, activity);
            notificationAsyncTask.execute(dormitoryBean.getId());

        }

        ((MyApplication)activity.getApplication()).setUpdateNotiHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch(msg.what) {
                case 0x101:
                    DormitoryBean dormitoryBean = ((MyApplication)activity.getApplication()).getDormitory();
                    if(dormitoryBean != null) {
                        NotificationAsyncTask notificationAsyncTask = new NotificationAsyncTask(mNortificationListAdapter, activity);
                        notificationAsyncTask.execute(dormitoryBean.getId());
                    }
                    break;
                }
            }
        });
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        /*if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private class NotificationAsyncTask extends AsyncTask<Integer, Object, List<NotificationBean>> {

        private NotificationListAdapter mNotificationListAdapter;
        private Activity activity;
        public NotificationAsyncTask(NotificationListAdapter notificationListAdapter, Activity activity) {
            mNotificationListAdapter = notificationListAdapter;
            this.activity = activity;
        }

        @Override
        protected List<NotificationBean> doInBackground(Integer[] params) {
            DormitoryController dormitoryController = DormitoryController.getInstance();
            try {
                return dormitoryController.getNotifications(params[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<NotificationBean> list) {
            super.onPostExecute(list);
            if(list == null) {
                Toast.makeText(activity, "网络错误", Toast.LENGTH_SHORT).show();
            }
            else
                mNotificationListAdapter.updateNotification(list);
            if(swipeRefreshLayout.isRefreshing())
                swipeRefreshLayout.setRefreshing(false);
        }
    }
}
